Skip to content

fix(elements-core): hash router ignores hash changes made by the host page (v9 regression) - #2850

Open
drewzhao wants to merge 1 commit into
stoplightio:mainfrom
drewzhao:fix-hash-router-navigation-in-web-components
Open

drewzhao wants to merge 1 commit into
stoplightio:mainfrom
drewzhao:fix-hash-router-navigation-in-web-components

Conversation

@drewzhao

@drewzhao drewzhao commented Nov 19, 2025 •

Copy link
Copy Markdown

With router="hash", Elements stops following navigation when it runs inside a page that has its own client-side router, such as a VitePress site. Clicking an operation in the table of contents updates the URL hash, but Elements keeps showing the previous page. Back and Forward still work.

This worked in 8.5.2, broke in 9.0.0 with the move to React Router 6 (8520585), and still happens in 9.0.29. Elements on a standalone page isn't affected.

Fixes #2792

Why it happens

React Router 6's hash history listens only for popstate. That's enough for ordinary hash links, because the browser fires popstate when it follows one.

Host routers often handle same-page links themselves. VitePress, for example, intercepts the click, calls preventDefault(), updates the URL with history.pushState(), and then dispatches a hashchange event (click handler, hash update). Because the click is already defaultPrevented, React Router's <Link> doesn't navigate either, and pushState() doesn't fire popstate. The router never sees the new hash.

Elements 8 used React Router 5, whose hash history also listened for hashchange. That's why this used to work.

What this PR changes

withRouter now renders a small internal component, HashRouterSync, next to the HashRouter it creates for router="hash". When a hashchange event arrives, it moves the router to the new hash:

  • It only follows hashes that are routes of this router: #/… under basePath, or an empty hash for the root. Other anchors on the host page, such as a skip link to #main-content, are left alone.
  • It removes basePath before calling navigate(), which adds it back.
  • It navigates with replace, because the host has already added the history entry.
  • It does nothing if the router is already at that location, for example after an ordinary hash link.

There's no API change and nothing new is exported. Other router types, and apps that render Elements inside their own router, aren't affected.

How to reproduce

Save this page and serve it locally, for example with python3 -m http.server. The script handles same-page hash links the way VitePress does.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Elements inside a host router</title>
    <script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css">
  </head>
  <body>
    <elements-api
      apiDescriptionUrl="https://raw.githubusercontent.com/stoplightio/Public-APIs/master/reference/zoom/openapi.yaml"
      router="hash"
      layout="sidebar"
    ></elements-api>

    <script>
      // Handle same-page hash links the way a host router such as VitePress does.
      window.addEventListener('click', (event) => {
        const link = event.target.closest('a[href^="#"]');
        if (!link) return;
        event.preventDefault();
        history.pushState({}, '', link.href);
        window.dispatchEvent(new HashChangeEvent('hashchange'));
      }, { capture: true });
    </script>
  </body>
</html>

With the published bundle (9.0.29), clicking an operation such as "List sub accounts" changes the URL to #/operations/accounts, but the page still shows the "Zoom API" overview. Point the first <script> at a build of this branch (packages/elements/dist/web-components.min.js) and the content follows each click.

Testing

  • HashRouterSync.spec.tsx adds 25 tests. They cover following a route hash, ignoring other anchors, an empty hash, query strings and in-page anchors, basePath, replace, no extra navigation after popstate, cleanup on unmount, and the withRouter wiring. One test shows that React Router alone ignores this kind of navigation. Reverting any of these behaviors in the implementation makes at least one test fail.
  • elements-core (415 tests), elements (50) and elements-dev-portal (18) pass. tsc --noEmit and ESLint are clean.
  • Without the withRouter change, a build of this branch is byte-identical to the published 9.0.29 web-components.min.js. With it, the bundle is 936 bytes larger.
  • In Chromium, I checked a VitePress 2.0.0-alpha.20 site, the page above, and a similar test page that adds a skip link to #main-content, with the default basePath and with basePath="/docs":
9.0.29 This PR
Click an operation URL changes, content doesn't Content follows
Back and Forward Work Work
Anchors on the host page (#VPContent in VitePress, #main-content) Left alone Left alone
Standalone page Works Works, unchanged

Out of scope

On a standalone page, the browser follows a host anchor such as #main-content itself and fires popstate, so React Router treats it as an unknown route. Elements then shows the first page with the default basePath, and nothing with a non-root basePath. This PR doesn't change that.

@drewzhao
drewzhao requested a review from a team as a code owner November 19, 2025 17:20
@netlify

netlify Bot commented Nov 19, 2025 •

Copy link
Copy Markdown

✅ Deploy Preview for stoplight-elements ready!

Name Link
🔨 Latest commit bedf975
🔍 Latest deploy log https://app.netlify.com/projects/stoplight-elements/deploys/697ca7dfe265be0008030a3f
😎 Deploy Preview https://deploy-preview-2850--stoplight-elements.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Nov 19, 2025 •

Copy link
Copy Markdown

✅ Deploy Preview for stoplight-elements-demo ready!

Name Link
🔨 Latest commit bedf975
🔍 Latest deploy log https://app.netlify.com/projects/stoplight-elements-demo/deploys/697ca7df9535a60008e1f121
😎 Deploy Preview https://deploy-preview-2850--stoplight-elements-demo.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@drewzhao
drewzhao force-pushed the fix-hash-router-navigation-in-web-components branch from d7eced4 to 9c10648 Compare January 7, 2026 14:01
@pedrosmr

Copy link
Copy Markdown

Hey folks, my team is stuck on version 8.5.2 because of the issue this PR solves. Any reason why it wasn't merged yet, considering it seems ready to go?

…mode

React Router v6's hash history listens to `popstate` only. Host routers that
change the URL with `history.pushState()` and then dispatch `hashchange` never
fire `popstate`, so the router keeps the old route while the URL shows the new
one. VitePress does this for every same-page link it intercepts: it calls
`preventDefault()`, so React Router's `<Link>` skips its own navigation, then
pushes the URL and dispatches a synthetic `HashChangeEvent`. Elements v8
worked because the history v4 hash history also listened to `hashchange`.
Back and Forward are unaffected, because a real history traversal fires
`popstate`.

Add HashRouterSync, rendered next to the HashRouter that withRouter creates
for `router="hash"`. On `hashchange` it moves the router to the new hash with
`replace`, because the host already created the history entry. It:

- acts only on hashes that are routes of this router (`#/...` under
  `basePath`, or an empty hash for the root), so a host page's own fragments,
  such as a skip link (`#main-content`), are left alone;
- strips `basePath` before calling `navigate()`, which adds it again;
- does nothing when the router is already at that location, for example
  after a native fragment navigation that React Router handled via `popstate`.

Fixes stoplightio#2792

Co-authored-by: Drew Zhao <drewzhao@outlook.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@drewzhao
drewzhao force-pushed the fix-hash-router-navigation-in-web-components branch from bedf975 to 5bb7ee1 Compare November 14, 2026 14:57
@drewzhao drewzhao changed the title fix(elements-core): HashRouter navigation doesn't update content in web component contexts fix(elements-core): hash router misses hashchange-only navigation from host pages (v9 regression) Nov 14, 2026
@drewzhao drewzhao changed the title fix(elements-core): hash router misses hashchange-only navigation from host pages (v9 regression) fix(elements-core): hash router ignores hash changes made by the host page (v9 regression) Nov 14, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HashRouter navigation doesn't update content in web component contexts (v9.0+ regression)

2 participants